package com.yuantu.judiciary.serviceimpl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.yuantu.judiciary.constant.Regulation;
import com.yuantu.judiciary.dao.*;
import com.yuantu.judiciary.exception.enums.*;
import com.yuantu.judiciary.model.domain.*;
import com.yuantu.judiciary.model.dto.*;
import com.yuantu.judiciary.model.enums.*;
import com.yuantu.judiciary.model.form.*;
import com.yuantu.judiciary.model.vo.QueryResultSimpleVO;
import com.yuantu.judiciary.service.*;
import com.yuantu.judiciary.utils.AssertUtil;
import com.yuantu.judiciary.utils.Sm2Util;
import com.yuantu.judiciary.utils.TimeUtil;
import com.yuantu.judiciary.utils.UrlUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * 短信模块接口实现
 *
 * @author syw
 * @since 2023-06-08
 **/
@Service
@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class SmsServiceImpl implements ISmsService {

    private final ISmsRecordDao smsRecordDao;
    private final IQueryRecordDao queryRecordDao;
    private final IQueryEntityDao queryEntityDao;
    private final IAccountDao accountDao;
    private final IOrganizationDao organizationDao;
    private final IAuthInfoDao authInfoDao;
    private final IUserInfoDao userInfoDao;
    private final ICheckResultService checkResultService;
    private final ISearchRecordService searchRecordService;
    private final IVipOrderDao vipOrderDao;
    private final IOperatorService operatorService;
    private final IPersonRemoveDao personRemoveDao;
    private final IAgentService agentService;

    @Override
    public Boolean sendCode(SendCodeForm form) {
        // 发送短信
        String phone = form.getPhone();
        String code = RandomStringUtils.randomNumeric(Regulation.SMS_CODE_LENGTH);
        SmsTemplateType templateType = SmsTemplateType.CODE;
        Boolean sendCode = sendMsgCode(phone, new SendCodeDataDTO(code), null, templateType);
        AssertUtil.assertTrue(Boolean.TRUE.equals(sendCode), SmsExceptionEnum.SMS_SEND_ERROR);
        // 查询并删除旧短信记录
        List<SmsRecordDO> smsRecords = smsRecordDao.findByPhoneAndTypeAndDeletedFalse(phone, templateType);
        if (!CollectionUtils.isEmpty(smsRecords)) {
            smsRecordDao.deleteByPhoneAndType(phone, templateType);
        }
        // 保存新短信记录
        SmsRecordDO smsRecord = buildSmsRecordDO(phone, code, templateType, null, null);
        smsRecordDao.save(smsRecord);
        return true;
    }

    @Override
    public Boolean verifyCode(VerifyCodeForm form) {
        // 校验验证码
        Timestamp currentTime = new Timestamp(System.currentTimeMillis());
        SmsRecordDO smsRecord = smsRecordDao.findOneByPhoneAndTypeAndContentAndExpiresTimeGreaterThanEqualAndDeletedFalse(
                form.getPhone(), SmsTemplateType.CODE, form.getCode(), currentTime
        );
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(smsRecord), SmsExceptionEnum.SMS_VERIFY_FAILURE);
        smsRecordDao.deleteByPhoneAndType(form.getPhone(), SmsTemplateType.CODE);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean sendAuthorizedCode(Long userId, EndpointType endpointType, SendAuthorizedCodeForm form) {
        SmsTemplateType templateType = SmsTemplateType.AUTHORIZED;
        String phone = form.getPhone();
        String name = form.getName();
        String idNumber = form.getIdNumber();
        AccountDO account = accountDao.findByIdAndDeletedFalse(userId);
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(account), AccountExceptionEnum.ACCOUNT_NOT_EXIST);
        OrganizationDO organization = organizationDao.findByIdAndDeletedFalse(account.getOrganizationId());
        String company = organization != null && OrganizationType.ENTER.equals(organization.getType()) ? organization.getEnterName() : account.getUsername();
        // 创建查询记录
        SearchRecordContentDTO searchRecord = new SearchRecordContentDTO(name, idNumber, phone);
        String content = JSON.toJSONString(searchRecord);
        QueryRecordDO queryRecord = queryRecordDao.findByCreatorIdAndTypeAndContentAndDeletedFalse(userId, SearchType.PERSON, content);
        boolean isUpdate = false;
        if (ObjectUtils.isEmpty(queryRecord)) {
            queryRecord = new QueryRecordDO();
            queryRecord.setCreatorId(userId);
            queryRecord.setContent(content);
            queryRecord.setType(SearchType.PERSON);
            queryRecord.setCodeInfo(form.getCodeInfo());
            queryRecord.setAuthorizedResult(AuthResultType.SEND_MSG);
            queryRecord.setExpiresTime(new Timestamp(System.currentTimeMillis() + (24 * 60 * 60 * 1000)));
            queryRecord.setOrigin(endpointType);
        } else {
            Timestamp currentTime = new Timestamp(System.currentTimeMillis());
            queryRecord.setLatestDataTime(currentTime);
            queryRecord.setCreateTime(currentTime);
            queryRecord.setExpiresTime(new Timestamp(System.currentTimeMillis() + (24 * 60 * 60 * 1000)));
            queryRecord.setAuthorizedResult(AuthResultType.SEND_MSG);
            isUpdate = true;
        }
        QueryEntityDO entity = getQueryEntity(userId, queryRecord, searchRecord);
        if (ObjectUtils.isEmpty(queryRecord.getEntityId()) || !queryRecord.getEntityId().equals(entity.getId())) {
            queryRecord.setEntityId(entity.getId());
        }
        queryRecordDao.save(queryRecord);

        if (isUpdate) {
            checkResultService.updateJsonDataProd(userId, QueryType.PER_BAD_RECORD, searchRecord, entity.getId());
            checkResultService.updateJsonDataProd(userId, QueryType.PER_JUDICIAL, searchRecord, entity.getId());
        }

        String smsContent = JSON.toJSONString(new AuthorizedInfoDTO(queryRecord.getId(), name, idNumber, phone, company, AuthType.QUERY));
        String uniqueShortUrl = UrlUtil.getUniqueShortUrl(Sm2Util.encrypt(smsContent));

//        String url = "https://cxb.learncoder.com/#/?sign=" + uniqueShortUrl + "，";
        String url = "https://admin.njxnet.com/face/#/?sign=" + uniqueShortUrl + "，";
        Boolean sendCode = sendMsgCode(form.getPhone(), null,
                new SendAuthorizedMsgDataDTO(name, company, url), templateType
        );
        AssertUtil.assertTrue(Boolean.TRUE.equals(sendCode), SmsExceptionEnum.SMS_SEND_ERROR);
        // 保存新短信记录
        SmsRecordDO smsRecord = buildSmsRecordDO(phone, smsContent, templateType, uniqueShortUrl, null);
        smsRecordDao.save(smsRecord);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean sendAuthorizedCodeByAli(Long userId, SendAuthorizedCodeForm form) {
        SmsTemplateType templateType = SmsTemplateType.AUTHORIZED;
        String phone = form.getPhone();
        String name = form.getName();
        String idNumber = form.getIdNumber();
        AccountDO account = accountDao.findByIdAndDeletedFalse(userId);
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(account), AccountExceptionEnum.ACCOUNT_NOT_EXIST);
        OrganizationDO organization = organizationDao.findByIdAndDeletedFalse(account.getOrganizationId());
        String company = organization != null && OrganizationType.ENTER.equals(organization.getType()) ? organization.getEnterName() : account.getUsername();
        // 创建查询记录
        SearchRecordContentDTO searchRecord = new SearchRecordContentDTO(name, idNumber, phone);
        String content = JSON.toJSONString(searchRecord);
        QueryRecordDO queryRecord = new QueryRecordDO();
        queryRecord.setCreatorId(userId);
        queryRecord.setContent(content);
        queryRecord.setType(SearchType.PERSON);
        queryRecord.setAuthorizedResult(AuthResultType.SEND_MSG);
        queryRecord.setOrigin(EndpointType.ALIPAY_APPLET);
        queryRecord.setExpiresTime(new Timestamp(System.currentTimeMillis() + (24 * 60 * 60 * 1000)));
        AssertUtil.assertTrue(StringUtils.isNotBlank(form.getTradeNo()), VipExceptionEnum.TRADE_NO_EMPTY);
        queryRecord.setTradeNo(form.getTradeNo());

        QueryEntityDO entity = getQueryEntity(userId, queryRecord, searchRecord);
        if (ObjectUtils.isEmpty(queryRecord.getEntityId()) || !queryRecord.getEntityId().equals(entity.getId())) {
            queryRecord.setEntityId(entity.getId());
        }
        queryRecordDao.save(queryRecord);

        String smsContent = JSON.toJSONString(new AuthorizedInfoDTO(queryRecord.getId(), name, idNumber, phone, company, AuthType.QUERY));
        String uniqueShortUrl = UrlUtil.getUniqueShortUrl(Sm2Util.encrypt(smsContent));

        String url = "https://admin.njxnet.com/face/#/?sign=" + uniqueShortUrl + "，";
        Boolean sendCode = sendMsgCode(form.getPhone(), null,
                new SendAuthorizedMsgDataDTO(name, company, url), templateType
        );
        AssertUtil.assertTrue(Boolean.TRUE.equals(sendCode), SmsExceptionEnum.SMS_SEND_ERROR);
        // 保存新短信记录
        SmsRecordDO smsRecord = buildSmsRecordDO(phone, smsContent, templateType, uniqueShortUrl, null);
        smsRecordDao.save(smsRecord);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long sendAuthorizedCodeBySelf(Long accountId, SendAuthorizedCodeForm form) {
        SmsTemplateType templateType = SmsTemplateType.REPORT;
        AccountDO account = accountDao.findByIdAndDeletedFalse(accountId);
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(account), AccountExceptionEnum.ACCOUNT_NOT_EXIST);
        UserInfoDO userInfo = userInfoDao.findByIdAndDeletedFalse(account.getUserId());
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(userInfo), UserExceptionEnum.USER_NOT_EXIST);
        String phone = userInfo.getPhone();
        String name = userInfo.getUserName();
        String idNumber = userInfo.getCertNo();
        OrganizationDO organization = organizationDao.findByIdAndDeletedFalse(account.getOrganizationId());
        String company = organization != null && OrganizationType.ENTER.equals(organization.getType()) ? organization.getEnterName() : account.getUsername();
        // 创建查询记录
        SearchRecordContentDTO searchRecord = new SearchRecordContentDTO(name, idNumber, phone);
        String content = JSON.toJSONString(searchRecord);
        Timestamp currentTime = new Timestamp(System.currentTimeMillis());
        QueryRecordDO queryRecord = new QueryRecordDO();
        queryRecord.setCreatorId(accountId);
        queryRecord.setContent(content);
        queryRecord.setType(SearchType.PERSON);
        queryRecord.setOrigin(EndpointType.ALIPAY_APPLET);
        AssertUtil.assertTrue(StringUtils.isNotBlank(form.getTradeNo()), VipExceptionEnum.TRADE_NO_EMPTY);
        queryRecord.setTradeNo(form.getTradeNo());
        queryRecord.setAuthorizedResult(AuthResultType.AUTHORIZED);
        queryRecord.setAuthorizedTime(currentTime);
        queryRecord.setExpiresTime(new Timestamp(currentTime.getTime() + (7 * 24 * 60 * 60 * 1000)));
        queryRecord.setSelf(true);
        QueryEntityDO entity = getQueryEntity(accountId, queryRecord, searchRecord);
        if (ObjectUtils.isEmpty(queryRecord.getEntityId()) || !queryRecord.getEntityId().equals(entity.getId())) {
            queryRecord.setEntityId(entity.getId());
        }
        queryRecordDao.save(queryRecord);

        //需要对可能存在的推荐码以及邀请人进行积分
        VipOrderDO vipOrderDO = vipOrderDao.findOrderByTradeNoAndDeletedFalse(queryRecord.getTradeNo());
        operatorService.updateHistoryScore(vipOrderDO);

        String smsContent = JSON.toJSONString(new AuthorizedInfoDTO(queryRecord.getId(), name, idNumber, phone, company, AuthType.QUERY));
        String uniqueShortUrl = UrlUtil.getUniqueShortUrl(Sm2Util.encrypt(smsContent));

        String url = "https://admin.njxnet.com/person/#/?sign=" + uniqueShortUrl;
        Boolean sendCode = sendMsgCode(form.getPhone(), null,
                new SendAuthorizedMsgDataDTO(name, company, url), templateType
        );
        AssertUtil.assertTrue(Boolean.TRUE.equals(sendCode), SmsExceptionEnum.SMS_SEND_ERROR);
        // 保存新短信记录
        SmsRecordDO smsRecord = buildSmsRecordDO(phone, smsContent, templateType, uniqueShortUrl, (long) (7 * 24 * 60 * 60 * 1000));
        smsRecordDao.save(smsRecord);
        return queryRecord.getId();
    }

    /**
     * 查自己
     *
     * @param accountId
     * @param codeInfo
     * @return
     */
    @Override
    public QueryResultSimpleVO sendAuthorizedCodeBySelfForWx(Long accountId, String codeInfo) {
        //SmsTemplateType templateType = SmsTemplateType.REPORT;
        AccountDO account = accountDao.findByIdAndDeletedFalse(accountId);
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(account), AccountExceptionEnum.ACCOUNT_NOT_EXIST);
        UserInfoDO userInfo = userInfoDao.findByIdAndDeletedFalse(account.getUserId());
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(userInfo), UserExceptionEnum.USER_NOT_EXIST);
        String phone = userInfo.getPhone();
        String name = userInfo.getUserName();
        String idNumber = userInfo.getCertNo();
        OrganizationDO organization = organizationDao.findByIdAndDeletedFalse(account.getOrganizationId());
        String company = organization != null && OrganizationType.ENTER.equals(organization.getType()) ? organization.getEnterName() : account.getUsername();
        //搜索记录
        AddSearchRecordForm addSearchRecord = new AddSearchRecordForm();
        SearchRecordContentDTO searchRecord = new SearchRecordContentDTO(name, idNumber, phone);
        addSearchRecord.setContent(searchRecord);
        addSearchRecord.setType(SearchType.PERSON);
        searchRecordService.add(account.getId(), addSearchRecord);
        // 创建查询记录
        String content = JSON.toJSONString(searchRecord);
        Timestamp currentTime = new Timestamp(System.currentTimeMillis());

        Date fiveMinutesAgo = new Date(System.currentTimeMillis() - 5 * 60 * 1000);
        List<QueryRecordDO> queryRecordList = queryRecordDao.findByCreatorIdAndContentAndDeletedFalseWithin5Minutes(accountId,content,fiveMinutesAgo);
        QueryRecordDO queryRecord = new QueryRecordDO();

        QueryResultSimpleVO queryResultSimple = new QueryResultSimpleVO();
        if(queryRecordList.size() > 0){
            queryRecord = queryRecordList.get(0);
        }else{
            queryRecord.setCreatorId(accountId);
            queryRecord.setContent(content);
            queryRecord.setType(SearchType.PERSON);
            queryRecord.setOrigin(EndpointType.APPLET);
            queryRecord.setAuthorizedResult(AuthResultType.AUTHORIZED);
            queryRecord.setAuthorizedTime(currentTime);
            queryRecord.setCodeInfo(codeInfo);
            queryRecord.setSelf(true);
            QueryEntityDO entity = getQueryEntity(accountId, queryRecord, searchRecord);
            if (ObjectUtils.isEmpty(queryRecord.getEntityId()) || !queryRecord.getEntityId().equals(entity.getId())) {
                queryRecord.setEntityId(entity.getId());
            }
            //当前应该消耗的套餐类型，当前平台为微信小程序 EndpointType.APPLET
            EndpointType endpointType = agentService.currentUseSearchTimeEndpoint(accountId, EndpointType.APPLET);
            if(endpointType.equals(EndpointType.H5)){
                String tradeNo = agentService.getOldestOrderTradeNo(accountId);
                queryRecord.setTradeNo(tradeNo);
            }
            queryRecordDao.save(queryRecord);
        }
        queryResultSimple.setId(queryRecord.getId());
        queryResultSimple.setIsShow(true);

//        if (personRemove == null) {
//            queryResultSimple.setIsShow(true);
//            // 保存新短信记录，认证成功则不需要去发短信了。
//            if (!(organization != null && organization.getAuthState().equals(AuthState.PASS))) {
//                String smsContent = JSON.toJSONString(new AuthorizedInfoDTO(queryRecord.getId(), name, idNumber, phone, company, AuthType.QUERY));
//                String uniqueShortUrl = UrlUtil.getUniqueShortUrl(Sm2Util.encrypt(smsContent));
//                String url = "https://admin.njxnet.com/person/#/?sign=" + uniqueShortUrl;
//                Boolean sendCode = sendMsgCode(userInfo.getPhone(), null,
//                        new SendAuthorizedMsgDataDTO(name, company, url), templateType
//                );
//                AssertUtil.assertTrue(Boolean.TRUE.equals(sendCode), SmsExceptionEnum.SMS_SEND_ERROR);
//                SmsRecordDO smsRecord = buildSmsRecordDO(phone, smsContent, templateType, uniqueShortUrl, (long) (7 * 24 * 60 * 60 * 1000));
//                smsRecordDao.save(smsRecord);
//            }
//        } else {
//            queryResultSimple.setIsShow(false);
//        }
        return queryResultSimple;
    }

    @Override
    public Boolean sendOrgAuthCode(Long accountId) {
        AccountDO account = accountDao.findByIdAndDeletedFalse(accountId);
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(account), AccountExceptionEnum.ACCOUNT_NOT_EXIST);
        OrganizationDO organization = organizationDao.findByIdAndDeletedFalse(account.getOrganizationId());
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(organization), OrganizationExceptionEnum.ORGANIZATION_NOT_EXIST);
        String company = OrganizationType.ENTER.equals(organization.getType()) ? organization.getEnterName() : account.getUsername();

        SearchRecordContentDTO searchRecord = new SearchRecordContentDTO(organization.getUsername(), organization.getIdNumber(), organization.getPhone());
        String content = JSON.toJSONString(searchRecord);
        // 保存认证信息
        AuthInfoDO authInfo = new AuthInfoDO();
        authInfo.setRelativeId(organization.getId());
        authInfo.setType(AuthType.REGISTER);
        authInfo.setOriginType(OriginType.ALI_WEB);
        authInfo.setContent(content);
        authInfoDao.save(authInfo);

        AuthorizedInfoDTO data = new AuthorizedInfoDTO(authInfo.getId(), organization.getUsername(),
                organization.getIdNumber(), organization.getPhone(), company, AuthType.REGISTER);

        return sendAuthCode(data);
    }

    @Override
    public Boolean sendAuthCode(AuthorizedInfoDTO authInfo) {
        SmsTemplateType templateType = SmsTemplateType.IDENTIFY;
        String smsContent = JSON.toJSONString(authInfo);
        String uniqueShortUrl = UrlUtil.getUniqueShortUrl(Sm2Util.encrypt(smsContent));

//        String url = "https://cxb.learncoder.com/#/?sign=" + uniqueShortUrl + "，";
        // String url = "https://admin.njxnet.com/face/#/?sign=" + uniqueShortUrl + "，";
        String url = "https://admin.njxnet.com/regFace/#/?sign=" + uniqueShortUrl + "，";
        Boolean sendCode = sendMsgCode(authInfo.getPhone(), null,
                new SendAuthorizedMsgDataDTO(authInfo.getName(), authInfo.getEnterpriseName(), url), templateType
        );
        AssertUtil.assertTrue(Boolean.TRUE.equals(sendCode), SmsExceptionEnum.SMS_SEND_ERROR);
        // 保存新短信记录
        SmsRecordDO smsRecord = buildSmsRecordDO(authInfo.getPhone(), smsContent, templateType, uniqueShortUrl, null);
        smsRecordDao.save(smsRecord);
        return true;
    }

    @Override
    public Boolean sendWarningCode(String count, String phone) {
        List<SmsRecordDO> records = smsRecordDao.findByPhoneAndTypeAndContentAndDeletedFalse(phone, SmsTemplateType.WARNING, count);
        if (CollectionUtils.isEmpty(records)) {
            // 发送短信
            SmsTemplateType templateType = SmsTemplateType.WARNING;
            Boolean sendCode = sendMsgCode(phone, new SendCodeDataDTO(count), null, templateType);
            AssertUtil.assertTrue(Boolean.TRUE.equals(sendCode), SmsExceptionEnum.SMS_SEND_ERROR);
            // 保存新短信记录
            SmsRecordDO smsRecord = buildSmsRecordDO(phone, count, templateType, null, null);
            smsRecordDao.save(smsRecord);
        }
        return true;
    }

    @Override
    public Boolean sendAuthorizedCodeAgain(Long accountId, SendAuthorizedCodeAgainForm form) {
        QueryRecordDO queryRecord = queryRecordDao.findByIdAndDeletedFalse(form.getId());
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(queryRecord), CheckPersonExceptionEnum.QUERY_RECORD_NOT_EXIST);
        AssertUtil.assertTrue(!AuthResultType.AUTHORIZED.equals(queryRecord.getAuthorizedResult()), CheckPersonExceptionEnum.QUERY_RECORD_AUTHORIZED);

        AccountDO account = accountDao.findByIdAndDeletedFalse(accountId);
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(account), AccountExceptionEnum.ACCOUNT_NOT_EXIST);
        UserInfoDO userInfo = userInfoDao.findByIdAndDeletedFalse(account.getUserId());
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(userInfo), UserExceptionEnum.USER_NOT_EXIST);
        OrganizationDO organization = organizationDao.findByIdAndDeletedFalse(account.getOrganizationId());
        String company = organization != null && OrganizationType.ENTER.equals(organization.getType()) ? organization.getEnterName() : account.getUsername();

        SearchRecordContentDTO searchRecord = JSON.parseObject(queryRecord.getContent(), SearchRecordContentDTO.class);
        searchRecord.setPhone(form.getPhone());
        String content = JSON.toJSONString(searchRecord);
        queryRecord.setContent(content);
        String smsContent = JSON.toJSONString(new AuthorizedInfoDTO(queryRecord.getId(), searchRecord.getName(), searchRecord.getIdNumber(), form.getPhone(), company, AuthType.QUERY));
        String uniqueShortUrl = UrlUtil.getUniqueShortUrl(Sm2Util.encrypt(smsContent));
        Boolean judgeSelf = searchRecord.getName().equals(userInfo.getUserName()) && searchRecord.getIdNumber().equals(userInfo.getCertNo());
        Timestamp currentTime = new Timestamp(System.currentTimeMillis());
        SmsTemplateType templateType;
        String url;
        Long expiresTime = null;
        if (Boolean.TRUE.equals(judgeSelf)) {
            queryRecord.setAuthorizedResult(AuthResultType.AUTHORIZED);
            queryRecord.setAuthorizedTime(currentTime);
            templateType = SmsTemplateType.REPORT;
            url = "https://admin.njxnet.com/person/#/?sign=" + uniqueShortUrl + "，";
            expiresTime = (long) (7 * 24 * 60 * 60 * 1000);
        } else {
            queryRecord.setAuthorizedResult(AuthResultType.SEND_MSG);
            templateType = SmsTemplateType.AUTHORIZED;
            url = "https://admin.njxnet.com/face/#/?sign=" + uniqueShortUrl + "，";
        }
        queryRecordDao.save(queryRecord);

        Boolean sendCode = sendMsgCode(form.getPhone(), null,
                new SendAuthorizedMsgDataDTO(searchRecord.getName(), company, url), templateType
        );
        AssertUtil.assertTrue(Boolean.TRUE.equals(sendCode), SmsExceptionEnum.SMS_SEND_ERROR);
        // 保存新短信记录
        SmsRecordDO smsRecord = buildSmsRecordDO(form.getPhone(), smsContent, templateType, uniqueShortUrl, expiresTime);
        smsRecordDao.save(smsRecord);
        return true;
    }

    @NotNull
    private QueryEntityDO getQueryEntity(Long userId, QueryRecordDO queryRecord, SearchRecordContentDTO searchRecord) {
        QueryEntityDO entity;
        if (ObjectUtils.isEmpty(queryRecord.getEntityId())) {
            entity = queryEntityDao.findByNameAndCodeAndTypeAndCreatorIdAndDeletedFalse(searchRecord.getName(), searchRecord.getIdNumber(), SearchType.PERSON, userId);
        } else {
            entity = queryEntityDao.findByIdAndDeletedFalse(queryRecord.getEntityId());
        }
        if (ObjectUtils.isEmpty(entity)) {
            entity = new QueryEntityDO(searchRecord.getName(), searchRecord.getIdNumber(), SearchType.PERSON);
            entity.setCreatorId(userId);
            queryEntityDao.save(entity);
        }
        return entity;
    }

    /**
     * 构建 SmsRecordDO
     */
    private SmsRecordDO buildSmsRecordDO(String phone, String content, SmsTemplateType type, String remarks, Long time) {
        SmsRecordDO smsRecord = new SmsRecordDO();
        smsRecord.setPhone(phone);
        smsRecord.setContent(content);
        smsRecord.setType(type);
        Timestamp currentTime = new Timestamp(System.currentTimeMillis());
        smsRecord.setCreateTime(currentTime);
        long expiresTime = time == null ? 300000 : time;
        smsRecord.setExpiresTime(new Timestamp(currentTime.getTime() + expiresTime));
        smsRecord.setRemarks(remarks);
        return smsRecord;
    }

    @Override
    public Boolean sendMsgCode(String phone, SendCodeDataDTO codeData, SendAuthorizedMsgDataDTO authorizedMsgData, SmsTemplateType templateType) {
        String url = "https://fy.njxnet.com:8085/api/phoneMsg/sendMsg";
//        String url = "http://47.100.124.208:8083/api/phoneMsg/sendMsg";
        SendCodeDTO sendCodeInfo = null;
        if (SmsTemplateType.CODE.equals(templateType)) {
            sendCodeInfo = buildSendCode(phone, codeData);
        } else if (SmsTemplateType.AUTHORIZED.equals(templateType)) {
            sendCodeInfo = buildSendAuthorizedMsg(phone, authorizedMsgData);
        } else if (SmsTemplateType.IDENTIFY.equals(templateType)) {
            sendCodeInfo = buildSendIdentifyMsg(phone, authorizedMsgData);
        } else if (SmsTemplateType.WARNING.equals(templateType)) {
            sendCodeInfo = buildWarningCode(phone, codeData);
        } else if (SmsTemplateType.REPORT.equals(templateType)) {
            sendCodeInfo = buildSendReportMsg(phone, authorizedMsgData);
        } else if (SmsTemplateType.COMPLAINT.equals(templateType)) {
            sendCodeInfo = buildSendComplaintMsg(phone, codeData);
        }
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(sendCodeInfo), SmsExceptionEnum.SMS_SEND_ERROR);
        // 发送短信
        String data = HttpUtil.post(url, JSON.toJSONString(sendCodeInfo));
        log.info("接口:【{}】, 参数:【{}】, 返回数据:【{}】", url, JSON.toJSONString(sendCodeInfo), data);
        if (StringUtils.isNotBlank(data)) {
            SendCodeResDTO sendCodeRes = JSON.parseObject(data, SendCodeResDTO.class);
            AssertUtil.assertTrue((!ObjectUtils.isEmpty(sendCodeRes) && 0 == sendCodeRes.getCode()), SmsExceptionEnum.SMS_SEND_ERROR);
            return true;
        }
        return false;
    }

    @Override
    public Boolean sendTimerMsgCode(String phone, SendTimerAuthDataDTO timerAuthData, SendTimerQueryDataDTO timerQueryData, SmsTemplateType templateType) {
        String url = "https://fy.njxnet.com:8085/api/phoneMsg/sendMsg";
//        String url = "http://47.100.124.208:8083/api/phoneMsg/sendMsg";
        SendCodeDTO sendCodeInfo = null;
        if (SmsTemplateType.TIMER_AUTH.equals(templateType)) {
            sendCodeInfo = buildSendTimerAuthMsg(phone, timerAuthData);
        } else if (SmsTemplateType.TIMER_QUERY.equals(templateType)) {
            sendCodeInfo = buildSendTimerQueryMsg(phone, timerQueryData);
        }
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(sendCodeInfo), SmsExceptionEnum.SMS_SEND_ERROR);
        // 发送短信
        String data = HttpUtil.post(url, JSON.toJSONString(sendCodeInfo));
        log.info("接口:【{}】, 参数:【{}】, 返回数据:【{}】", url, JSON.toJSONString(sendCodeInfo), data);
        if (StringUtils.isNotBlank(data)) {
            SendCodeResDTO sendCodeRes = JSON.parseObject(data, SendCodeResDTO.class);
            AssertUtil.assertTrue((!ObjectUtils.isEmpty(sendCodeRes) && 0 == sendCodeRes.getCode()), SmsExceptionEnum.SMS_SEND_ERROR);
            return true;
        }
        return false;
    }

    @Override
    public Boolean sendAuthSuccess(String phone, String cxr, String bcxr) {
        //SmsTemplateType templateType = SmsTemplateType.AUTH_SUCCESS;
        String url = "https://fy.njxnet.com:8085/api/phoneMsg/sendMsg";
        SendCodeDTO sendCodeInfo = buildAuthSuccessMsg(phone, cxr, bcxr);
        AssertUtil.assertTrue(!ObjectUtils.isEmpty(sendCodeInfo), SmsExceptionEnum.SMS_SEND_ERROR);
        // 发送短信
        String data = HttpUtil.post(url, JSON.toJSONString(sendCodeInfo));
        log.info("授权成功通知短信接口:【{}】, 参数:【{}】, 返回数据:【{}】", url, JSON.toJSONString(sendCodeInfo), data);
        return true;
    }

    private SendCodeDTO buildSendComplaintMsg(String phone, SendCodeDataDTO codeData) {
        SendCodeDTO data = new SendCodeDTO();
        data.setCourtCode("100001");
        data.setData(JSON.toJSONString(codeData));
        data.setMobile(phone);
        data.setSendType("2");
        data.setType("fxb_6");
        return data;
    }

    private SendCodeDTO buildSendTimerAuthMsg(String phone, SendTimerAuthDataDTO codeData) {
        SendCodeDTO data = new SendCodeDTO();
        data.setCourtCode("100001");
        data.setData(JSON.toJSONString(codeData));
        data.setMobile(phone);
        data.setSendType("2");
        data.setType("fxb_8");
        return data;
    }

    private SendCodeDTO buildSendTimerQueryMsg(String phone, SendTimerQueryDataDTO codeData) {
        SendCodeDTO data = new SendCodeDTO();
        data.setCourtCode("100001");
        data.setData(JSON.toJSONString(codeData));
        data.setMobile(phone);
        data.setSendType("2");
        data.setType("fxb_9");
        return data;
    }

    private SendCodeDTO buildSendCode(String phone, SendCodeDataDTO codeData) {
        SendCodeDTO data = new SendCodeDTO();
        data.setCourtCode("100001");
        data.setData(JSON.toJSONString(codeData));
        data.setMobile(phone);
        data.setSendType("2");
        data.setType("fxb_1");
        return data;
    }

    private SendCodeDTO buildSendAuthorizedMsg(String phone, SendAuthorizedMsgDataDTO authorizedMsgData) {
        SendCodeDTO data = new SendCodeDTO();
        data.setCourtCode("100001");
        data.setData(JSON.toJSONString(authorizedMsgData));
        data.setMobile(phone);
        data.setSendType("2");
        data.setType("fxb_2");
        return data;
    }

    private SendCodeDTO buildSendIdentifyMsg(String phone, SendAuthorizedMsgDataDTO authorizedMsgData) {
        SendCodeDTO data = new SendCodeDTO();
        data.setCourtCode("100001");
        data.setData(JSON.toJSONString(new SendIdentifyMsgDataDTO("", authorizedMsgData.getUrl().replace("，", ""))));
        data.setMobile(phone);
        data.setSendType("2");
        data.setType("fxb_3");
        return data;
    }

    private SendCodeDTO buildWarningCode(String phone, SendCodeDataDTO codeData) {
        SendCodeDTO data = new SendCodeDTO();
        data.setCourtCode("100001");
        data.setData(JSON.toJSONString(new SendWarningDTO(codeData.getValidNumber())));
        data.setMobile(phone);
        data.setSendType("2");
        data.setType("fxb_4");
        return data;
    }

    private SendCodeDTO buildSendReportMsg(String phone, SendAuthorizedMsgDataDTO authorizedMsgData) {
        SendCodeDTO data = new SendCodeDTO();
        data.setCourtCode("100001");
        long currentTime = System.currentTimeMillis();
        String startTime = TimeUtil.transferTimeString(new Timestamp(currentTime), Regulation.WHOLE_TIME);
        String endTime = TimeUtil.transferTimeString(new Timestamp(currentTime + (7 * 24 * 60 * 60 * 1000)), Regulation.WHOLE_TIME);
        data.setData(JSON.toJSONString(new SendReportDTO(authorizedMsgData.getName(), startTime, authorizedMsgData.getUrl(), endTime)));
        data.setMobile(phone);
        data.setSendType("2");
        data.setType("fxb_5");
        return data;
    }

    private SendCodeDTO buildAuthSuccessMsg(String phone, String cxr, String bcxr) {
        SendCodeDTO data = new SendCodeDTO();
        data.setCourtCode("100001");
        data.setData(JSON.toJSONString(new SendAuthSuccessDTO(cxr, bcxr)));
        data.setMobile(phone);
        data.setSendType("2");
        data.setType("fxb_7");
        return data;
    }

}
